<template>
	<div class="course_exam_wrapper" v-loading="loading">
		<div class="course_exam_content">
			<el-scrollbar>
				<template v-if="!loading">
					<el-statistic format="HH:mm:ss" :value="examTime" title="倒计时" time-indices />
				</template>
				<h1>{{ examData.name }}</h1>
				<el-row :gutter="16">
					<el-col :span="12">考试总分：{{ examData.total }}分</el-col>
					<el-col :span="12">及格分数：{{ examData.passScore }}分</el-col>
				</el-row>
				<dl v-for="(item, index) in examChapters" :key="index">
					<dt>{{ item.title }}</dt>
					<dd>
						<template v-for="(n, i) in item.children">
							<el-button size="mini" :type="n.answer | buttonType" @click="handleLocateAnchor(`${index}${i}`)">{{ i + 1 }}</el-button>
						</template>
					</dd>
				</dl>
			</el-scrollbar>
			<div class="button">
				<el-button size="medium" type="primary" @click="handleSubmitPager()">交卷</el-button>
				<el-button size="medium" @click="handleReturnCourse()">返回</el-button>
			</div>
		</div>
		<el-scrollbar class="course_exam_subject">
			<subject-chapter v-if="examChapters.length > 0" :data="examChapters">
				<template slot-scope="{ data, index, anchor }">
					<subject-item :s-index="index" :anchor="`anchor${anchor}`" :data="data"></subject-item>
				</template>
			</subject-chapter>
			<el-empty v-else :image="noexam" :image-size="150" description="暂无试题"></el-empty>
		</el-scrollbar>
		<div class="course_exam_button">
			<el-button size="medium" type="primary" @click="handleSubmitPager()">交卷</el-button>
			<el-button size="medium" @click="handleReturnCourse()">返回</el-button>
		</div>
		<exam-report v-model="reportDialog" :result-id="examResultId" is-exam></exam-report>
	</div>
</template>

<script>
import lodash from 'lodash';
import moment from 'moment';
import subjectItem from './subject';
import subjectChapter from './chapter';
import examReport from '@/views/common/reportCard';
import { genExamPaper, submitExamPaper } from '@/api/exam/testExam';
export default {
	components: { subjectChapter, subjectItem, examReport },
	data() {
		return {
			loading: false,
			examTime: 0,
			examData: {},
			examChapters: [],
			noexam: require('@/assets/img/noexam.svg'),
			reportDialog: false,
			examResultId: ''
		};
	},
	computed: {
		examId() {
			return this.$route.query.id;
		},
		submitMessage() {
			return (arr) => {
				let message = '本试卷共';
				let subjectsLen = arr.length;
				let answer = arr.filter((n) => n.answer.length > 0);
				message += `<font color="#f00"><strong>${subjectsLen}</strong></font>`;
				message += `道题，已答<font color="#f00"><strong>${answer.length}</strong></font>`;
				return `${message}题，确定要交卷吗？`;
			};
		}
	},
	filters: {
		buttonType(data) {
			if (data.length > 0) {
				return 'primary';
			}
			return '';
		}
	},
	watch: {
		examId: {
			handler(id) {
				this.loading = true;
				this.queryExamDetail(id);
			},
			immediate: true
		}
	},
	methods: {
		//获取考试详情
		async queryExamDetail(id) {
			let result = await genExamPaper(id).then((res) => res.data);
			this.loading = false;
			if (result.code === '0') {
				let datas = this.$detailData(result.data);
				let duration = parseInt(datas.examDuration);
				let testPaper = datas.testPaper || {};
				this.examTime = moment().add(duration, 'minutes').valueOf();
				this.examData = { ...datas, total: testPaper?.totalScore || '0' };
				this.examChapters = this.formatPaperData(testPaper?.testPaperChapterList || []);
				this.handleAddedExamPeriod();
			}
		},

		//格式化试卷题目
		formatPaperData(arr) {
			return arr.map((item) => {
				let chapter = { title: item.title };
				chapter['children'] = item.testSubjectVO.map((n, i) => {
					let subject = n.testSubjects || {};
					let obj = { id: n.id, title: subject.title };
					obj['answer'] = subject.type === '2' ? [] : '';
					obj['options'] = subject?.subjectOptionsVOList || [];
					return { ...obj, score: n.score, subjectsType: subject.type };
				});
				return chapter;
			});
		},

		//格式化试题数据
		formatSubjectData() {
			let subjects = [];
			let fields = ['id', 'score', 'answer', 'subjectsType'];
			this.examChapters.forEach((item) => {
				let children = item.children.map((n) => lodash.pick(n, fields));
				subjects = [...subjects, ...children];
			});
			return subjects;
		},

		//格式化提交参数
		formatSubmitParams(subject) {
			let params = { testExam: this.examData };
			params['testPaperAnswerVOList'] = subject;
			return { ...params, testExamId: this.examId };
		},

		//提交试卷请求
		async submitPaperRequest(subject) {
			let params = this.formatSubmitParams(subject);
			let result = await submitExamPaper(params).then((res) => res.data);
			if (result.code === '0') {
				let datas = this.$detailData(result.data);
				this.handleAddedExamPeriod();
				this.examResultId = datas.id;
				this.reportDialog = true;
			}
		},

		//添加考试学时
		handleAddedExamPeriod() {
			let duration = parseInt(this.examData.examDuration);
			let params = { resId: this.examId, durationType: 'E' };
			params['duration'] = Math.round((duration / 60) * 100) / 100;
			this.$store.dispatch('addedDurationRecord', params);
		},

		//提交试卷
		handleSubmitPager() {
			let subject = this.formatSubjectData();
			this.$alert(this.submitMessage(subject), '提交试卷', {
				showCancelButton: true,
				dangerouslyUseHTMLString: true,
				beforeClose: async (action, instance, done) => {
					if (action === 'confirm') {
						instance.confirmButtonLoading = true;
						await this.submitPaperRequest(subject);
						instance.confirmButtonLoading = false;
					}
					done();
				}
			}).catch(() => {});
		},

		//点击定位锚点
		handleLocateAnchor(anchor) {
			let dom = document.querySelector(`#anchor${anchor}`);
			!!dom && dom.scrollIntoView({ behavior: 'smooth' });
		},

		//返回课程
		handleReturnCourse() {
			this.$router.back();
		}
	}
};
</script>

<style lang="scss" scoped>
.course_exam_wrapper {
	display: flex;
	flex-direction: row-reverse;
	height: calc(100vh - 60px);
}
.course_exam_subject::v-deep {
	flex: 1;
	height: 100% !important;
	background-color: #f0f0f0;
	.el-scrollbar__wrap {
		overflow-x: hidden;
	}
	.el-scrollbar__view {
		padding: 10px;
		box-sizing: border-box;
		&:has(.el-empty) {
			justify-content: center;
		}
	}
}
.course_exam_content::v-deep {
	display: flex;
	flex-direction: column;
	width: 320px;
	flex-shrink: 0;
	box-sizing: border-box;
	height: 100% !important;
	border-left: solid 1px #ebeef5;
	.el-scrollbar {
		flex: 1;
		overflow: hidden;
	}
	.el-scrollbar__wrap {
		overflow-x: hidden;
	}
	.el-scrollbar__view {
		overflow: hidden;
	}
	.el-statistic {
		display: flex;
		align-items: center;
		flex-direction: column;
		justify-content: center;
		flex-shrink: 0;
		padding: 24px 0;
		background-color: #f5f5f5;
		border-bottom: solid 1px #ebeef5;
		.head {
			display: block;
			color: #909399;
			line-height: 1;
			margin-bottom: 10px;
		}
		.number {
			display: block;
			font-size: 48px;
			color: #303133;
			line-height: 0.65;
			font-family: 'ds-digital-bold';
		}
	}
	h1 {
		padding: 0 12px;
		font-size: 20px;
		margin-top: 12px;
	}
	.el-row {
		padding: 12px;
		color: #606266;
		border-bottom: solid 1px #ebeef5;
	}
	dl {
		margin-top: 20px;
		padding-left: 12px;
		dt {
			line-height: 1;
			font-weight: bold;
		}
		dd {
			display: flex;
			align-items: center;
			flex-wrap: wrap;
		}
		.el-button {
			font-size: 16px;
			padding: 5px 9px;
			margin: 12px 12px 0 0;
		}
	}
	.button {
		display: flex;
		align-items: center;
		justify-content: center;
		flex-shrink: 0;
		padding: 16px;
		border-top: solid 1px #ebeef5;
		.el-button {
			width: 100%;
			font-size: 18px;
		}
	}
}
.course_exam_button {
	display: none;
}
@media screen and (max-width: 768px) {
	.course_exam_wrapper {
		height: auto;
		flex-direction: column;
	}
	.course_exam_content::v-deep {
		width: 100%;
		border-left: none;
		.el-scrollbar__view {
			padding-bottom: 6px;
		}
		.el-statistic {
			padding: 20px 0;
		}
		.button {
			display: none;
			padding: 12px;
		}
		dl {
			display: none;
		}
	}
	.course_exam_subject::v-deep {
		height: auto !important;
		.el-scrollbar__view {
			padding: 0 0 6px;
		}
	}
	.course_exam_button {
		display: flex;
		align-items: center;
		justify-content: center;
		flex-shrink: 0;
		padding: 12px;
		border-top: solid 1px #ebeef5;
		.el-button {
			width: 100%;
			font-size: 16px;
		}
	}
}
</style>
